<!--
  * 舆情文章列表页面
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2025-01-15 10:00:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <!---------- 查询表单 begin ----------->
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row" v-privilege="'yuqing:article:query'">
      <a-form-item label="关键词搜索" class="smart-query-form-item">
        <a-input 
          style="width: 200px" 
          v-model:value="queryForm.keyword" 
          placeholder="请输入关键词" 
          @pressEnter="onSearch"
        />
      </a-form-item>

      <a-form-item label="搜索范围" class="smart-query-form-item">
        <a-checkbox-group v-model:value="queryForm.searchScope" :options="searchScopeOptions" />
      </a-form-item>

      <a-form-item label="情感倾向" class="smart-query-form-item">
        <a-select 
          style="width: 120px" 
          v-model:value="queryForm.sentiment" 
          :options="sentimentOptions"
          placeholder="请选择"
        />
      </a-form-item>

      <a-form-item label="发布时间" class="smart-query-form-item">
        <a-range-picker 
          v-model:value="publishTimeRange" 
          style="width: 240px"
          @change="onPublishTimeChange"
        />
      </a-form-item>

      <a-form-item label="作者" class="smart-query-form-item">
        <a-input 
          style="width: 120px" 
          v-model:value="queryForm.author" 
          placeholder="作者姓名"
          @pressEnter="onSearch"
        />
      </a-form-item>

      <a-form-item class="smart-query-form-item">
        <a-button-group>
          <a-button type="primary" @click="onSearch" v-privilege="'yuqing:article:query'">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" v-privilege="'yuqing:article:query'">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单 end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="confirmBatchDelete" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'yuqing:article:delete'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>

        <a-button @click="onExport" type="primary" v-privilege="'yuqing:article:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出数据
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="'YUQING_ARTICLE'" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    
    <a-table
      size="small"
      :dataSource="tableData"
      :columns="columns"
      rowKey="articleId"
      :scroll="{ x: 1200, y: 600 }"
      bordered
      :pagination="false"
      :showSorterTooltip="false"
      :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
      :loading="tableLoading"
    >
      <template #bodyCell="{ text, record, column }">
        <template v-if="column.dataIndex === 'title'">
          <a @click="showDetail(record)" style="color: #1890ff; cursor: pointer;">
            {{ text }}
          </a>
        </template>
        
        <template v-if="column.dataIndex === 'content'">
          <div class="article-content">
            {{ text }}
          </div>
        </template>
        
        <template v-if="column.dataIndex === 'sentiment'">
          <a-tag :color="getSentimentInfo(record.sentiment).color">
            {{ getSentimentInfo(record.sentiment).desc }}
          </a-tag>
        </template>
        
        <template v-if="column.dataIndex === 'publishTime'">
          {{ formatDate(text) }}
        </template>
        
        <template v-if="column.dataIndex === 'sourceUrl'">
          <a :href="text" target="_blank" v-if="text">
            查看原文
          </a>
        </template>
        
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="showDetail(record)" type="link" v-privilege="'yuqing:article:detail'">详情</a-button>
            <a-button @click="deleteArticle(record)" danger type="link" v-privilege="'yuqing:article:delete'">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>

    <!-- 文章详情弹窗 -->
    <ArticleDetailModal ref="detailModal" />
  </a-card>
</template>

<script setup>
  import ArticleDetailModal from './components/article-detail-modal.vue';
  import { onMounted, reactive, ref } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SearchOutlined, ReloadOutlined, DeleteOutlined, ExportOutlined } from '@ant-design/icons-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { newsArticleApi } from '/@/api/business/yuqing/news-article-api';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { SEARCH_SCOPE_OPTIONS, SENTIMENT_OPTIONS, getSentimentInfo } from '/@/constants/business/yuqing/yuqing-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import _ from 'lodash';
  import dayjs from 'dayjs';

  // ---------------------------- 表格列配置 ----------------------------
  const columns = ref([
    {
      title: '文章标题',
      dataIndex: 'title',
      width: 300,
      ellipsis: true,
    },
    {
      title: '内容摘要',
      dataIndex: 'content',
      width: 400,
      ellipsis: true,
    },
    {
      title: '作者',
      dataIndex: 'author',
      width: 100,
    },
    {
      title: '发布时间',
      dataIndex: 'publishTime',
      width: 150,
    },
    {
      title: '情感倾向',
      dataIndex: 'sentiment',
      width: 100,
    },
    {
      title: '查看次数',
      dataIndex: 'viewCount',
      width: 80,
    },
    {
      title: '原文链接',
      dataIndex: 'sourceUrl',
      width: 100,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 120,
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------
  const queryFormState = {
    keyword: '',
    searchScope: ['title', 'content', 'author'], // 默认全选
    sentiment: '',
    publishStartTime: null,
    publishEndTime: null,
    author: '',
    pageNum: 1,
    pageSize: 10,
  };

  // 查询表单
  const queryForm = reactive(_.cloneDeep(queryFormState));
  
  // 发布时间范围
  const publishTimeRange = ref([]);
  
  // 搜索范围选项
  const searchScopeOptions = SEARCH_SCOPE_OPTIONS;
  
  // 情感倾向选项
  const sentimentOptions = SENTIMENT_OPTIONS;
  
  // 表格加载状态
  const tableLoading = ref(false);
  
  // 表格数据
  const tableData = ref([]);
  
  // 总数
  const total = ref(0);
  
  // 选中的行
  const selectedRowKeyList = ref([]);

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, _.cloneDeep(queryFormState));
    queryForm.pageSize = pageSize;
    publishTimeRange.value = [];
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 发布时间范围改变
  function onPublishTimeChange(dates) {
    if (dates && dates.length === 2) {
      queryForm.publishStartTime = dates[0].startOf('day').format('YYYY-MM-DD HH:mm:ss');
      queryForm.publishEndTime = dates[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
    } else {
      queryForm.publishStartTime = null;
      queryForm.publishEndTime = null;
    }
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      let queryResult = await newsArticleApi.queryPage(queryForm);
      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  onMounted(queryData);

  // ---------------------------- 详情查看 ----------------------------
  const detailModal = ref();

  function showDetail(record) {
    detailModal.value.showDetail(record.articleId);
  }

  // ---------------------------- 删除相关 ----------------------------
  function deleteArticle(record) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除这篇文章吗？',
      okText: '删除',
      okType: 'danger',
      onOk() {
        singleDelete(record);
      },
      cancelText: '取消',
    });
  }

  async function singleDelete(record) {
    try {
      SmartLoading.show();
      await newsArticleApi.delete(record.articleId);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // 选择表格行
  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  // 批量删除
  function confirmBatchDelete() {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中的文章吗？',
      okText: '删除',
      okType: 'danger',
      onOk() {
        batchDelete();
      },
      cancelText: '取消',
    });
  }

  async function batchDelete() {
    try {
      SmartLoading.show();
      await newsArticleApi.batchDelete(selectedRowKeyList.value);
      message.success('删除成功');
      selectedRowKeyList.value = [];
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 导出数据 ----------------------------
  async function onExport() {
    try {
      SmartLoading.show();
      let exportQuery = { ...queryForm };
      delete exportQuery.pageNum;
      delete exportQuery.pageSize;
      
      await newsArticleApi.export(exportQuery);
      message.success('导出成功');
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 工具方法 ----------------------------
  function formatDate(date) {
    return date ? dayjs(date).format('YYYY-MM-DD HH:mm') : '';
  }
</script>

<style scoped>
.article-content {
  max-width: 400px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.smart-table-operate .ant-btn {
  margin-right: 10px;
}

.smart-table-operate .ant-btn:last-child {
  margin-right: 0;
}
</style> 